package pers.zh.parking.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.zh.parking.dao.ParkingLotMapper;
import pers.zh.parking.dao.ParkingSpaceMapper;
import pers.zh.parking.enums.SpaceStatus;
import pers.zh.parking.po.ParkingLot;
import pers.zh.parking.po.ParkingSpace;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpaceService implements ISpaceService {

    @Autowired
    ParkingSpaceMapper spaceMapper;
    @Autowired
    ParkingLotMapper lotMapper;

    @Override
    public boolean batchGenerate(List<ParkingLot> lots) {
        for (ParkingLot lot : lots) {
            List<ParkingSpace> spaceList = new ArrayList<>();
            // 每个停车场生成2000个车位，并设置状态，同时设置每个停车场车位情况
            for (int i = 1; i <= 2000; i++) {
                ParkingSpace space = new ParkingSpace();
                space.setSpaceId(i);
                space.setSpaceNo(i);
                space.setLotId(lot.getLotId());
                if (i % 2 == 0) {
                    space.setStatus(SpaceStatus.FREE.toString());
                } else {
                    space.setStatus(SpaceStatus.USING.toString());
                }
                if (i % 11 == 0) {
                    space.setStatus(SpaceStatus.DESPERATE.toString());
                }
                spaceList.add(space);
            }
            if (spaceMapper.batchGenerate(spaceList) <= 0) {
                return false;
            }
            lotMapper.batchUpdateSpace(lotMapper.getAllLotIds());
        }
        return  true;
    }

    @Override
    public ParkingSpace getRandomFreeSpace(Integer lotId) {
        return spaceMapper.getRandomFreeSpace(lotId);
    }

    @Override
    public boolean isFull(Integer lotId) {
        return spaceMapper.freeCount(lotId) == 0;
    }

    @Override
    public List<ParkingSpace> getSpacesByLotId(int lotId) {
        return spaceMapper.getSpacesByLotId(lotId);
    }

    @Override
    public boolean update(ParkingSpace space) {
        return spaceMapper.updateByPrimaryKeySelective(space) > 0;
    }

    @Override
    public boolean add(ParkingSpace space) {
        // 车位状态，1：空闲；2：在用；3：预约中
        space.setStatus("1");
        space.setSpaceId(spaceMapper.genSpaceId(space.getLotId()));
        space.setSpaceNo(spaceMapper.genSpaceNo(space.getLotId()));
        return spaceMapper.insert(space) > 0;
    }

    @Override
    public boolean batchDel(List<ParkingSpace> list) {
        return spaceMapper.batchDelete(list) > 0;
    }
}
